/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package putime.newspaperagent.stock;

import java.awt.Container;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import putime.model.ModelStock;

/**
 *
 * @author Khai
 */
public class AddStock extends javax.swing.JDialog {

    ModelStock modelStock = new ModelStock();

    /**
     * Creates new form AddStock
     */
    public AddStock(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        initSup();
        java.util.Date date = new java.util.Date();
        txtDate.setDate(date);
    }

    public void initSup() {
        Vector vSup = modelStock.initSupAdd();
        DefaultComboBoxModel dcm = new DefaultComboBoxModel(vSup);
        cobSupplier.setModel(dcm);
        changeSupplier();
    }

    public void changeSupplier() {
        Vector vPro = new Vector();
        try {
            String tam = String.valueOf(cobSupplier.getSelectedItem());
            tam = tam.substring(0, tam.indexOf(" "));
            int chon = Integer.parseInt(tam);
            vPro = modelStock.initProAdd(chon);
            DefaultComboBoxModel dcm = new DefaultComboBoxModel(vPro);
            cobProduct.setModel(dcm);
        } catch (Exception e) {
        }
    }

    public boolean CheckValidate() {
        Pattern patter = Pattern.compile("^\\d[\\d\\.]*");
        Matcher matcher = patter.matcher(txtRate.getText().trim());
        if (!matcher.matches()) {
            JOptionPane.showMessageDialog(this, "Wrong Rate!, Please iput again!","False",0);
            return false;
        }

        patter = Pattern.compile("\\d+");
        matcher = patter.matcher(txtInWard.getText().trim());
        if (!matcher.matches()) {
            JOptionPane.showMessageDialog(this, "Wrong Qty Inward!, Please iput again!","False",0);
            return false;
        }

        matcher = patter.matcher(txtReturn.getText().trim());
        if (!matcher.matches()) {
            JOptionPane.showMessageDialog(this, "Wrong Qty Return!, Please iput again!","False",0);
            return false;
        }

        return true;

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtDate = new com.toedter.calendar.JDateChooser();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        btnAdd = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        cobSupplier = new javax.swing.JComboBox();
        txtInWard = new javax.swing.JTextField();
        txtReturn = new javax.swing.JTextField();
        cobProduct = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        txtRate = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Date");

        jLabel2.setText("Supplier");

        jLabel3.setText("Product");

        jLabel4.setText("Qty InWard");

        jLabel5.setText("Returned");

        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        cobSupplier.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cobSupplier.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cobSupplierItemStateChanged(evt);
            }
        });

        cobProduct.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel6.setText("Rate");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(54, 54, 54)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(46, 46, 46)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtDate, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(8, 8, 8)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(cobProduct, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(cobSupplier, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtRate, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(146, 146, 146)
                        .addComponent(btnAdd)
                        .addGap(68, 68, 68)
                        .addComponent(btnCancel))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(58, 58, 58)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel5)
                            .addComponent(jLabel4)
                            .addComponent(jLabel6))
                        .addGap(31, 31, 31)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtReturn, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE)
                            .addComponent(txtInWard))))
                .addContainerGap(157, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(txtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(50, 50, 50)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cobSupplier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(89, 89, 89)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cobProduct, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txtRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtInWard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtReturn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAdd)
                    .addComponent(btnCancel))
                .addGap(24, 24, 24))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cobSupplierItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cobSupplierItemStateChanged
        changeSupplier();
    }//GEN-LAST:event_cobSupplierItemStateChanged

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        String tam = String.valueOf(cobSupplier.getSelectedItem());
        tam = tam.substring(0, tam.indexOf(" "));
        int supID = Integer.parseInt(tam);
        String proID = String.valueOf(cobProduct.getSelectedItem());
        proID = proID.substring(0, proID.indexOf(" "));
        SimpleDateFormat sdf = new SimpleDateFormat();
        Date date;
        try {
            date = new Date(Date.parse(sdf.format(txtDate.getDate())));
        } catch (NullPointerException e) {
            JOptionPane.showMessageDialog(this, "You must input the correct Hire Date formats: MMM d, yyyy ");
            return;
        }

        if (!modelStock.checkExist(supID, proID, date)) {
            JOptionPane.showMessageDialog(this, "Supplier and Product is added","False",0);
            return;
        }
        if (!CheckValidate()) {
            return;
        }


        float rate = Float.parseFloat(txtRate.getText());
        int inward = Integer.parseInt(txtInWard.getText());
        int returned = Integer.parseInt(txtReturn.getText());

        if (inward - returned < 0) {
            JOptionPane.showMessageDialog(this, "Qty Inward must larger or equal Qty Return","False",0);
            return;
        }

        boolean isAdd = modelStock.addStock(date, supID, proID, rate, inward, returned);
        if (isAdd) {
            JOptionPane.showMessageDialog(this, "Add successfully");
        } else {
            JOptionPane.showMessageDialog(this, "Fail !!!","False",0);
        }

    }//GEN-LAST:event_btnAddActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed

        frmStock parent = (frmStock) this.getParent();
        parent.initCalendar();
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AddStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AddStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AddStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AddStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                AddStock dialog = new AddStock(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnCancel;
    private javax.swing.JComboBox cobProduct;
    private javax.swing.JComboBox cobSupplier;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private com.toedter.calendar.JDateChooser txtDate;
    private javax.swing.JTextField txtInWard;
    private javax.swing.JTextField txtRate;
    private javax.swing.JTextField txtReturn;
    // End of variables declaration//GEN-END:variables
}
